import { Component, OnInit, ViewChild } from '@angular/core';
import { listModel, addDrawingsModel, imgType } from './drawings.model';
import { DrawingsService } from '../../../services/project/drawings/drawings.service';
import { ZzjFileUploader, FlowFileModel } from '@zzj/nag-file-uploader';
import { FILEURL } from './../../../config';
import { NzModalService, NzMessageService } from 'ng-zorro-antd';
import { ModelListService } from '../../../services/project/model/model-list.service';
import { Router, ActivatedRoute } from '@angular/router';
import { Utils } from 'src/app/common/helper/util-helper';
import { FileUploaderComponent } from '../../../components/file-uploader/file-uploader.component';

@Component({
  selector: 'app-drawings',
  templateUrl: './drawings.component.html',
  styleUrls: ['./drawings.component.scss']
})
export class DrawingsComponent implements OnInit {

  @ViewChild('imageUploader',{ static: false }) imageUploader: FileUploaderComponent;

  constructor(
    private drawingsService: DrawingsService,
    private modalService: NzModalService,
    private modelListService: ModelListService,
    private router: Router,
    private message: NzMessageService,
    private routeInfo: ActivatedRoute
  ) { }


  public APDInfo = JSON.parse(window.localStorage.getItem('APDInfo'));
  public project = JSON.parse(window.localStorage.getItem('project'));
  public projectName: string = this.project.name;
  public createUserId = this.project.creatorUserId;
  // 用于渲染的图纸文件列表
  public drawingsLists: any = [];
  // 缓存图纸文件列表
  public imgUpLists: any = [];
  // 记录图纸文件总数
  public nzTotal = 0;
  // 默认分页
  public nzPageIndex = 1;

  // 分页查询参数类
  public findJson = new listModel();
  // 添加图纸弹窗
  public isAddVisible = false;
  // 上传组件文件队列
  public fileQueue: any = [];
  // 添加图纸类
  public addDrawingsModel = new addDrawingsModel();
  // public modelLists: any = [];
  // 控制上传按钮显示内容
  public imgShow = true;
  // 编辑图纸弹窗
  public isEditVisible = false;
  // 编辑图纸文件类
  public editDrawingsModel = new addDrawingsModel();

  public addLoading = false;
  // input aceccpt 属性
  public imgType: any = imgType;
  // 一个图纸文件对应一个modelGroupId
  public modelGroupId: any = '';
  public status = {
    // 所需项目级权限
    PIpagePermissions: [
      // 图纸管理
      'APJ.PI.Drawings',
    ],
    // 当前页面项目级权限状态
    PIpageAuthorty: {
      PIDrawings: null,
    }
  };

  /**
   * 初始化
   */
  public async init() {
    if (this.APDInfo['roleCode'] !== 'Admin' && this.APDInfo.userId !== this.createUserId) {
      this.status.PIpageAuthorty = Utils.PIgrantedPermissions(
        this.status.PIpagePermissions,
        this.status.PIpageAuthorty,
        true
      )
    } else {
      // admin 角色拥有该页面权限
      // tslint:disable-next-line: forin
      for (const key in this.status.PIpageAuthorty) {
        console.log(key)
        this.status.PIpageAuthorty[key] = true;
      }
    }
    // 获取图纸列表
    this.findJson.projectId = this.project.id;
    const result = await this.drawingsService.getDrawingsLists(this.findJson);
    if (result.success) {
      this.drawingsLists = result.result.items;
      this.nzTotal = result.result.totalCount;
    }
  }

  public async pageChange(index) {
    this.findJson.skipCount = index - 1;
    this.init();
  }

  public async search() {
    this.findJson.skipCount = 0;
    await this.init();
  }

  /**
   * 添加图纸
   */
  public addDrawings() {
    this.isAddVisible = true;
    this.imgShow = true;
    this.modelGroupId = this.getGuid()
  }

  public async fileChange(e) {
    this.imgUpLists.forEach(el => {
      if (e.target.files[0].name === el.name) {
        this.fileSuccess(el);
        return;
      }
    });
    this.imageUploader.add(e.target.files[0]);
  }

  // 文件上传成功回调
  public async fileSuccess(transfer: FlowFileModel) {

    this.imgUpLists.push(transfer);
    // const arr = transfer.fileInfo.path.split('.');
    // this.addDrawingsModel.modelUrl = arr[0] + '/';
    this.addDrawingsModel.path = transfer.fileInfo.path;
    this.addDrawingsModel.fileId = transfer.fileInfo.id;
    this.addDrawingsModel.size = transfer.size;
    // this.addDrawingsModel.creatorUserName = this.APDInfo.userName;
    this.addDrawingsModel.modelGroupId = this.modelGroupId;
    this.addDrawingsModel.hash = transfer.fileInfo.hash;
    this.addDrawingsModel.fileName = transfer.name;
    this.addDrawingsModel.projectId = this.project.id;
    this.addDrawingsModel.SSOCreatorUserId = transfer.fileInfo.createdUserId;
    this.addDrawingsModel.type = transfer.fileInfo.type,
    this.imgShow = false;

  }
  // 保存图纸上传
  public async handleAddOk() {
    this.addLoading = true;
    if (this.imgShow) {
      this.message.create('warning', '请上传图纸');
      return;
    }

    // 保存文件相关属性用于图形转换，业务后台保存
    console.log(this.addDrawingsModel);
    await this.drawingsService.addDrawings(this.addDrawingsModel).then((res) => {
      if (res.success) {
        // this.message.success('上传成功');
        this.addDrawingsModel = new addDrawingsModel();
      } else {
        this.message.error(Utils.errorMessageProcessor(res) || '上传失败');
      }
    });
    // 调用图纸类型转换接口
    const parmas = {
      modelGroupId: this.modelGroupId,
      projectId: this.project.id,
    }
    const resultAna = await this.drawingsService.ConvertModel(parmas)
    if (resultAna.success) {
      this.message.success('保存成功');
    } else {
      this.message.error(Utils.errorMessageProcessor(resultAna) || '保存失败');
    }
    this.addLoading = false;
    this.isAddVisible = false;
    this.init();
  }

  /**
   * 修改
   * @param item
   */
  public editDrawings(item) {
    this.isEditVisible = true;
    this.editDrawingsModel = new addDrawingsModel(item);
  }

  public async handleEditOk() {
    this.isEditVisible = false;
    await this.drawingsService.editDrawings(this.editDrawingsModel);
    this.init();
  }

  public handleCancel() {
    this.isAddVisible = false;
    this.isEditVisible = false;
  }

  /**
   * 删除
   * @param item
   */
  public async deleteDrawings(item) {
    this.modalService.error({
      nzTitle: '确认要删除这个图纸吗?',
      nzContent: '<b style="color: red;">删除后不能恢复，请谨慎操作。</b>',
      nzOkText: '确定',
      nzOkType: 'danger',
      nzOnOk: async () => {
        // 业务端删除
        const delRes = await this.drawingsService.deleteDrawings({ input: item.id });
        const Params = {
          hash: item.hash,
          modelGroupId: item.modelGroupId,
          modelName: item.fileName
        }
        //  图形后台删除
        await this.modelListService.delModelFromGraphicsServer(Params).then((res) => {
          if (res.success && delRes.success) {
            this.message.success('删除成功');
          } else {
            this.message.error(Utils.errorMessageProcessor(res) || Utils.errorMessageProcessor(delRes) || '保存失败');
          }
        })

        this.init();
      },
      nzCancelText: '取消',
      nzOnCancel: () => { }
    });
  }

  /**
   * 打开图纸
   */
  public async openDrawings(item) {
    console.log(item);
    if (!item.taskId) {
    }
    const json = {
      ModelGroupId: item.modelGroupId,
      taskId: item.taskId
    }
    // 查询解析进度
    const result = await this.modelListService.transformation(json);
    if (!result.item.taskState.successed) {
      this.message.create('warning', result.item.taskState.message);
      return;
    }
    result.item.modelList.forEach(el => {
      if (el.percent == 0) {
        this.message.create('warning', `图纸  ` + '【' + el.modelName + '】' + el.errorMessage);
      }

    });
    // 缓存图纸并跳转
    window.localStorage.setItem('drawings', JSON.stringify(item));
    this.routeInfo.queryParams.subscribe(queryParams => {
      const projectId = this.project.id;
      this.router.navigate([`inner/project/${projectId}/view`], { queryParams });
    });
  }

  routeToSurvey() {
    const projectId = this.project.id;
    this.router.navigate([`/inner/project/${projectId}/survey`], { queryParams: { info: 'project' } });
  }



  /**
    * 前端生成Guid
    * @private
    * @returns
    */
  private getGuid() {
    let s = [];
    const hexDigits = '0123456789abcdef';
    for (let i = 0; i < 36; i++) {
      s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = '4'; // bits 12-15 of the time_hi_and_version field to 0010
    // tslint:disable-next-line: no-bitwise
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
    s[8] = s[13] = s[18] = s[23] = '-';
    let uuid = s.join('');
    return uuid;
  }


  ngOnInit() {
    this.init()
  }

}
